

package jframe.utils;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.compass.core.util.reader.StringReader;

/**
 * @描述:<p>Jaxb操作工具类</p>
 *
 * @作者: 叶平平(yepp)
 *
 * @时间: 2011-11-6 下午02:51:39
 */
public class XmlUtil {
	
	private JAXBContext context;
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;
	
	public XmlUtil(Class<?> clazz){
		try {
			this.context = JAXBContext.newInstance(clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String java2Xml(Object obj){
		StringWriter sw = new StringWriter();
		try {
			this.marshaller = context.createMarshaller();
			this.marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			this.marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
			marshaller.marshal(obj, sw);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return  sw.toString().replace(" standalone=\"yes\"", "");
	}
	
	public Object xml2Java(String xml){
		Object obj = null;
		try {
			this.unmarshaller = context.createUnmarshaller();
			StringReader  reader = new StringReader(xml);
			obj = unmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
